09. Exercise: Methods (Part 1)

Methods Exercise (Part 1)

addNumbers

Task Description:

In this exercise you will be creating a simple addNumbers method, like the example we just looked at. The method should take two numbers as input, add them together, and then return the result.

Since you're new to the Java syntax, we've given step-by-step guidance below—but we recommend that you try to type out as much of the syntax as you can from your own memory (i.e., don't just copy and paste it) as this will help you to learn it.

Task List:

Task Feedback:

Nice work!

Code

If you need a code on the https://github.com/udacity.

  • userCode:

    export PATH=/data/jdk-15.0.1/bin:$PATH
    export JAVA_HOME=/data/jdk-15.0.1/bin

  • Solution

    You can find both a video and text below containing the solution.

    You'll see that the video demonstrates the code in IntelliJ. The only significant difference is that in the workspace you need to compile and run the code using the terminal, whereas in IntelliJ you can simply click Run.

    ND079 C1 L1 A09 Solution 1

    public class FunctionExercise {
    
        public static void main(String[] args) {
    
            System.out.println(FunctionExercise.addNumbers(7, 7));
        }
    
        // Add your function here:
        public static int addNumbers(int num1, int num2) {
            return num1 + num2;
        }
    }